import React from 'react';
import { InputNumber, Modal, Select, Space, ConfigProvider, Popconfirm } from 'antd';
import zhCN from 'antd/es/locale/zh_CN';
import _ from 'lodash';
import moment from 'moment';

import { CalendarOutlined } from '#/utils/antdIcons.js';
import TRNotification from '#/utils/notification.js';
import { TRDefault } from '@/components/index.js';

import { AdjustTable } from '../../../BaseTable';
import CheckedList from '../../../CheckedList';
import { tableHead_2, OPTION_KEY, imgString_3 } from '../../../../helper.js';
import styles from './index.less';

const MySelect = (props: any) => {
  const { value = [], onChange, options = [] } = props;
  return (
    <div style={{ position: 'relative' }}>
      <Select
        showSearch={false}
        value={value}
        options={options}
        style={{ width: 200, fontSize: 12 }}
        placeholder="选择参考年份"
        mode="multiple"
        maxTagCount={2}
        maxTagTextLength={4}
        onChange={onChange}
        dropdownRender={() =>
          options.length ? (
            <CheckedList options={options} onChange={onChange} value={value} />
          ) : (
            <TRDefault type="emptysm" />
          )
        }
      />
      <CalendarOutlined className={styles.icon_calendar} />
    </div>
  );
};
const ModalComponent = ({ onPress, referencePowerData, referenceYearOptions }: any) => {
  const [visible, setVisible] = React.useState(true),
    [show, setShow] = React.useState(false),
    [referenceYear, setReferenceYear] = React.useState<any>(),
    [referencePowerOption, setReferencePowerOption] = React.useState<any>(),
    [referencePower, setReferencePower] = React.useState<any>(),
    [AdjustmentOption, setAdjustmentOption] = React.useState<any>(),
    [Adjustment, setAdjustment] = React.useState<any>(0),
    [tableData, setTableData] = React.useState<any>([]),
    [value, setValue] = React.useState<any>(0),
    [dataAll, setDataAll] = React.useState<any>();

  React.useEffect(() => {
    setDataAll(_.cloneDeep(referencePowerData));
    const _temp = referencePowerData.map((t: any) => ({
      label: t.title,
      value: t.title,
    }));
    setReferenceYear(referenceYearOptions.map((t: any) => t.value));
    setReferencePowerOption(_temp);
    setAdjustmentOption([
      { label: '上调', value: 0 },
      { label: '下调', value: 1 },
      { label: '全部重置', value: 2 },
    ]);
  }, []);

  const _title = () => {
    return (
      <div className={styles.title}>
        <img src={imgString_3} />
        <div className={styles.iconText}>一键调整</div>
      </div>
    );
  };

  const _onCancel = () => {
    if (!show && value) {
      setShow(true);
      return;
    }
    setVisible(false);
    onPress({ index: 0 });
  };

  const _onOk = () => {
    const _temp: any = {
      index: 1,
      checkedData: tableData[0],
    };
    //全部重置
    if (Adjustment === 2) {
      _temp.clear = 1;
    }
    onPress(_temp);
  };

  const onInputChange = (data: any) => {
    setValue(data);

    //上调
    if (Adjustment === 0) {
      let _temp = _.cloneDeep(dataAll.filter((t: any) => t.title === referencePower));
      _temp = _temp.map((t: any) => {
        Object.values(OPTION_KEY).forEach((_t: any) => {
          t[_t] = parseFloat(
            ((data / 100) * parseFloat(t[_t] || 0) + parseFloat(t[_t] || 0)) as any,
          ).toFixed(1);
        });
        return t;
      });
      setTableData(_temp);
    }
    //下调
    else if (Adjustment === 1) {
      let _temp = _.cloneDeep(dataAll.filter((t: any) => t.title === referencePower));
      _temp = _temp.map((t: any) => {
        Object.values(OPTION_KEY).forEach((_t: any) => {
          t[_t] = parseFloat(
            (((-1 * data) / 100) * parseFloat(t[_t] || 0) + parseFloat(t[_t] || 0)) as any,
          ).toFixed(1);
        });
        return t;
      });
      setTableData(_temp);
    }
  };
  const onPowerchange = (e: any) => {
    setTableData(referencePowerData.filter((t: any) => t.title === e));
    setReferencePower(e);
  };
  const onYearChange = (e: any) => {
    const temp = dataAll
      .filter((t: any) => {
        return e.some((_t: any) => t.title.includes(_t));
      })
      .map((t: any) => ({ label: t.title, value: t.title }));
    setReferencePowerOption(temp);
    setReferenceYear(e);
  };
  const onConfirm = () => {
    setVisible(false);
    onPress({ index: 0 });
  };
  return (
    <Modal
      width={733}
      className={styles.modal}
      visible={visible}
      centered={true}
      maskClosable={true}
      title={_title()}
      onCancel={_onCancel}
      cancelText={
        <Popconfirm
          placement="top"
          visible={show}
          onCancel={(e) => {
            e?.stopPropagation();
            setShow(false);
          }}
          title={'提示：当前工作将不被保存，继续执行此操作？'}
          onConfirm={onConfirm}
          okText="确认"
          cancelText="取消"
        >
          取消
        </Popconfirm>
      }
      okText={'确定'}
      onOk={_onOk}
    >
      <ConfigProvider locale={zhCN}>
        <Space size={[12, 8]} wrap>
          <MySelect value={referenceYear} options={referenceYearOptions} onChange={onYearChange} />
          <Select
            value={referencePower}
            style={{ width: 120, fontSize: 12 }}
            placeholder="选择参考电量"
            options={referencePowerOption}
            onChange={(e) => {
              onPowerchange(e);
            }}
          />
          <Select
            value={Adjustment}
            style={{ width: 120, fontSize: 12 }}
            placeholder="上调"
            options={AdjustmentOption}
            onChange={(e) => {
              setAdjustment(e);
            }}
          />
          <InputNumber
            value={value}
            defaultValue={value}
            min={0}
            style={{ width: 120, fontSize: 12 }}
            max={100}
            step={0.1}
            formatter={(val) => `${val}%`}
            parser={(val) => val!.replace('%', '')}
            onChange={onInputChange}
          />
        </Space>
        {tableData.length ? (
          <>
            <div className={styles.cell}>
              <span className={styles.title}>
                {moment().format('YYYY')}年计划电量 <span className={styles.unit}>单位：MWh</span>
              </span>
            </div>
            <AdjustTable tableData={tableData} tableHeader={tableHead_2} />
          </>
        ) : (
          <TRDefault type="emptysm" />
        )}
      </ConfigProvider>
    </Modal>
  );
};
class AdjustScale {
  __key__ = '';

  show = (props: any) => {
    return new Promise((resolve) => {
      if (this.__key__ !== '') return;
      this.__key__ = String(Date.now());
      TRNotification.add({
        key: this.__key__,
        content: (
          <ModalComponent
            {...props}
            onPress={(result: any) => {
              TRNotification.remove(this.__key__);
              this.__key__ = '';
              resolve(result);
            }}
          />
        ),
        duration: null,
      });
    });
  };

  dismiss = () => {
    if (this.__key__.length > 0) {
      TRNotification.remove(this.__key__);
      this.__key__ = '';
    }
  };
}

export default new AdjustScale();
